<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 1、导入mapbox的依赖 -->
    <script src="https://lib.baomitu.com/Turf.js/latest/turf.min.js"></script>
    <script src='https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.js'></script>
    <link href='https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.css' rel='stylesheet' />
    <style>
        * {
            margin: 0;
            padding: 0
        }

        #map {
            width: 100vw;
            height: 100vh;
        }

        #clear {
            width: 200px;
            height: 50px;
            position: fixed;
            top: 20px;
            right: 50px;
            z-index: 100;
        }
    </style>
</head>

<body>
    <!-- 2、设置地图容器的挂载点 -->
    <button id="clear" onclick="clearLayer()">清除数据</button>
    <div id="map">

    </div>
    <script>
        /* token */
        mapboxgl.accessToken = 'pk.eyJ1IjoiZXJpYzA5MTciLCJhIjoiY2x3cTI2Zzg0MWY2dDJqcWVpdDI1MHNpcCJ9.k9gLW7ZgLyISNdYHIEEGdQ'
        const map = new mapboxgl.Map({
            /* target-ol */
            container: 'map', // container ID
            /* style-layers */
            style: 'mapbox://styles/mapbox/streets-v12', // style URL
            center: [114.30, 30.50], // starting position [lng, lat]
            zoom: 12, // starting zoom
        });
        var data = {
            type: "FeatureCollection",
            features: []
        }
        map.on("style.load", () => {
            map.addSource("p_source", {
                type: "geojson",
                data
            })
            map.addLayer({
                id: "p_layer",
                source: "p_source",
                type: "circle",
                paint: {
                    'circle-color': "red",
                    'circle-radius': 15
                }
            })
        })

        map.on("click", evt => {
            var { lng, lat } = evt.lngLat;
            var feature = turf.point([lng, lat]);
            data.features.push(feature);
            var source = map.getSource("p_source");
            source.setData(data);
        })
        function clearLayer() {
            data.features = [];
            var source = map.getSource("p_source");
            source.setData(data);
        }
    </script>
</body>

</html>